package com.zrrd.mcl.mq.receiver;

import com.rabbitmq.client.Channel;
import com.zrrd.mcl.mq.config.DelayedMqConfig;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Configuration
public class MqReceiver {

    //接收消息的方法
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "queue.mcl", autoDelete = "false"),
            exchange = @Exchange(value = "exchange.mcl", autoDelete = "true"),
            key = {"routing.mcl"}
    ))
    public void getMsg(Message message, Channel channel) throws IOException {
        //打印消息内容
        System.out.println("收到了消息=====>");
        byte[] body = message.getBody();
        String msg = new String(body);
        System.out.println(msg);
        //使用手动方式回执
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    //接收延迟消息
    @RabbitListener(queues = DelayedMqConfig.queue_delay_1)
    public void getMsg2(String msg, Message message, Channel channel) throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-Mm-dd HH:mm:ss");
        System.out.println("收到了延迟消息===>" + msg);
        System.out.println("收到延迟消息时间====>" + sdf.format(new Date()));
        //消息回执
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
